<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true" label-width="68px">
      <el-form-item label="线索来源" prop="sources">
        <el-input v-model="queryParams.sources" placeholder="请输入线索来源" clearable style="width: 240px"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="线索性质" prop="nature">
        <el-input v-model="queryParams.nature" placeholder="请输入线索性质" clearable style="width: 240px"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="处理进展" prop="processingProgress">
        <el-select v-model="queryParams.processingProgress" placeholder="教育背景" clearable style="width: 240px"
          @keyup.enter="handleQuery">
          <el-option v-for="(dict, key) in sys_normal_disable.processingProgress" :key="key" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:role:add']">新增</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格数据 -->
    <el-table v-loading="loading" :data="clueList" row-key="id" @selection-change="handleSelectionChange"
      @expand-change="handleExpandChange" @current-change="handleCurrentChange">
      <el-table-column type="expand">
        <template #default="props">
          <div style="margin-left: 2rem;">
            <el-table :data="props.row.people">
              <el-table-column label="编号" prop="id" width="180" />
              <el-table-column label="姓名" prop="name" :show-overflow-tooltip="true" />
              <el-table-column label="年龄" prop="age" :show-overflow-tooltip="true" />
              <el-table-column label="性别" prop="sex" :show-overflow-tooltip="true" />
              <el-table-column label="身份证号" prop="idCard" :show-overflow-tooltip="true" show-password />
              <el-table-column label="联系方式" prop="phone" :show-overflow-tooltip="true" />
              <el-table-column label="联系方式" prop="phone" :show-overflow-tooltip="true" />
              <el-table-column label="施暴者" prop="personnelType" width="120" fixed="right">
                <template #default="scope">
                  <el-switch v-model="scope.row.personnelType" active-text="是" inactive-text="否" inline-prompt disabled/>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="编号" prop="id" width="180" />
      <el-table-column label="线索来源" prop="sources" width="160" />
      <el-table-column label="线索性质" prop="nature" width="140" />
      <el-table-column label="线索价值" prop="clueValue" width="140" />
      <el-table-column label="线索内容" prop="context" />
      <el-table-column label="处理进展" prop="processingProgress" width="140">
        <template #default="scope">
          <el-tag
            :type="sys_normal_disable.processingProgress.filter(e => e.value == scope.row.processingProgress)[0].type"
            disable-transitions>{{ scope.row.processingProgress }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="140">
        <template #default="scope">
          <el-tooltip content="修改" placement="top" v-if="scope.row.id !== '1'">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
              v-hasPermi="['system:role:edit']"></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top" v-if="scope.row.id !== '1'">
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
              v-hasPermi="['system:role:remove']"></el-button>
          </el-tooltip>
          <el-tooltip content="关联人员" placement="top" v-if="scope.row.id !== '1'">
            <el-button link type="primary" icon="user" @click="handlePersonnel(scope.row)"
              v-hasPermi="['system:user:resetPwd']"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改资料配置对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="roleRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="线索来源" prop="sources">
          <el-input type="textarea" v-model="form.sources" placeholder="请输入线索来源" />
        </el-form-item>
        <el-form-item label="线索性质" prop="nature">
          <el-input v-model="form.nature" placeholder="请输入线索性质" />
        </el-form-item>
        <el-form-item label="线索价值" prop="clueValue">
          <el-input v-model="form.clueValue" placeholder="请输入线索价值" />
        </el-form-item>
        <el-form-item label="线索内容" prop="context">
          <el-input type="textarea" v-model="form.context" placeholder="请输入线索内容" />
        </el-form-item>
        <el-form-item label="处理进展" prop="processingProgress">
          <el-select v-model="form.processingProgress" placeholder="选择处理进展" clearable style="width: 100%">
            <el-option v-for="(dict, key) in sys_normal_disable.processingProgress" :key="key" :label="dict.label"
              :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.id != undefined" prop="people">
          <el-table :data="form.people">
            <el-table-column label="编号" prop="id" width="180" />
            <el-table-column label="姓名" prop="name" :show-overflow-tooltip="true" />
            <el-table-column label="身份证号" prop="idCard" :show-overflow-tooltip="true" show-password />
            <el-table-column label="施暴者" prop="personnelType" width="120" fixed="right">
              <template #default="scope">
                <el-switch v-model="scope.row.personnelType" active-text="是" inactive-text="否" inline-prompt/>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 绑定人员配置对话框 -->
    <el-dialog title="人员列表" v-model="openPersonnel" width="1000px" append-to-body>

      <el-form :model="queryParamsPersonnel" ref="queryRefPersonnel" v-show="showSearch" :inline="true"
        label-width="68px">
        <el-form-item label="人员姓名" prop="name">
          <el-input v-model="queryParamsPersonnel.name" placeholder="请输入人员姓名" clearable style="width: 240px"
            @keyup.enter="handleQueryPersonnel" />
        </el-form-item>
        <el-form-item label="身份证号" prop="idCard">
          <el-input v-model="queryParamsPersonnel.idCard" placeholder="请输入身份证号" clearable style="width: 240px"
            @keyup.enter="handleQueryPersonnel" />
        </el-form-item>
        <el-form-item label="联系方式" prop="phone">
          <el-input v-model="queryParamsPersonnel.phone" placeholder="请输入联系方式" clearable style="width: 240px"
            @keyup.enter="handleQueryPersonnel" />
        </el-form-item>
        <el-form-item label="教育背景" prop="edBackground">
          <el-select v-model="queryParamsPersonnel.edBackground" placeholder="教育背景" clearable style="width: 240px">
            <el-option v-for="(dict, key) in sys_normal_disable.edBackground" :key="key" :label="dict.label"
              :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQueryPersonnel">搜索</el-button>
          <el-button icon="Refresh" @click="resetQueryPersonnel">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格数据 -->
      <el-table v-loading="loadingPersonnel" 
        ref="table_personnel"
        :data="personnelList"
        show-overflow-tooltip
        @selection-change="handleSelectionChangePersonnel" >
        <el-table-column type="selection" width="55" align="center" fixed="left" />
        <el-table-column label="编号" prop="id" width="180" />
        <el-table-column label="姓名" prop="name" :show-overflow-tooltip="true" width="120" />
        <el-table-column label="年龄" prop="age" :show-overflow-tooltip="true" width="80" />
        <el-table-column label="性别" prop="sex" :show-overflow-tooltip="true" width="80" />
        <el-table-column label="身份证号" prop="idCard" :show-overflow-tooltip="true" width="200" show-password />
        <el-table-column label="联系方式" prop="phone" :show-overflow-tooltip="true" width="150" />
        <el-table-column label="监护人" prop="guardianName" width="150" />
        <el-table-column label="教育背景" prop="edBackground" width="150" />
        <el-table-column label="施暴者" prop="personnelType" width="120" fixed="right">
          <template #default="scope">
            <el-switch v-model="scope.row.personnelType" active-text="是" inactive-text="否" inline-prompt />
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="totalPersonnel > 0" :total="totalPersonnel" v-model:page="queryParamsPersonnel.pageNo"
        v-model:limit="queryParamsPersonnel.pageSize" @pagination="getListPersonnel" />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFormPersonnel">绑 定</el-button>
          <el-button @click="cancelpersonnel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Clue">
import { addClue, delClue, listClue, updateClue, associationClue, selectPersonnelInfo } from "@/api/system/clue";
import { listPersonnel } from "@/api/system/personnel";
import useUserStore from '@/store/modules/user'

const { proxy } = getCurrentInstance();
const sys_normal_disable = {
  edBackground: [
    { label: '初中及以下', value: '初中及以下' },
    { label: '高中', value: '高中' },
    { label: '大专', value: '大专' },
    { label: '本科', value: '本科' },
    { label: '硕士', value: '硕士' },
    { label: '博士', value: '博士' }
  ],
  processingProgress: [
    { label: '待确认', value: '待确认', type: 'danger' },
    { label: '跟进中', value: '跟进中', type: 'warning' },
    { label: '已完成', value: '已完成', type: 'success' }
  ]
};

const clueList = ref([]);
const personnelList = ref([]);
const open = ref(false);
const openPersonnel = ref(false);

const loading = ref(true);
const loadingPersonnel = ref(true);
const showSearch = ref(true);
const ids = ref([]);
let idsPersonnel = [];
const multiple = ref(true);
const total = ref(0);
const totalPersonnel = ref(0);
const title = ref("");
let curIds = ref({});

const data = reactive({
  form: {},
  queryParams: {
    pageNo: 1,
    pageSize: 10,
    name: undefined,
    sources: undefined,
    nature: undefined,
    clueValue: undefined,
  },
  queryParamsPersonnel: {
    pageNo: 1,
    pageSize: 10,
    name: undefined,
    idCard: undefined,
    phone: undefined,
    edBackground: undefined,
  },
  rules: {
    // name: [{ required: true, message: "人员姓名不能为空", trigger: "blur" }],
    // idCard: [{ required: true, pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, message: "身份证号不正确", trigger: "blur" }],
    // edBackground: [{ required: true, message: "教育背景不能为空", trigger: "blur" }],
    // phone: [{ required: true, pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }]
  },
});

let table_personnel = ref("table_personnel");

const { queryParams, queryParamsPersonnel, form, rules } = toRefs(data);

/** 查询线索列表 */
function getList() {
  loading.value = true;
  listClue(queryParams.value).then(res => {
    // proxy.$modal.msgSuccess("查询成功");
    const users = res.result
    clueList.value = users.records;
    total.value = users.total;
    loading.value = false;
  });
}

/** 查询人员列表 */
function getListPersonnel(row) {
  loadingPersonnel.value = true;
  listPersonnel(queryParamsPersonnel.value).then(res => {
    // proxy.$modal.msgSuccess("查询成功");
    const users = res.result
    personnelList.value = users.records;
    totalPersonnel.value = users.total;
    loadingPersonnel.value = false;

    nextTick(()=> {
      selectPersonnelInfo(row.id).then(e => {
        e.result.forEach(i => {
          let _target = personnelList.value.find(item => item.id == i.id);
          _target.personnelType = i.personnelType;
          table_personnel.value.toggleRowSelection(personnelList.value.find(item => item.id == i.id),true)
        })
      }) 
    })
  });
}

/** 展开 */
async function handleExpandChange(row, expandedRows) {
  if(expandedRows.find(e => e.id == row.id) != undefined){
    queryParams.value.pageNo = 1;
    let res = await selectPersonnelInfo(row.id)
    clueList.value.forEach(e => {
      if (e.id == row.id) {
        e.people = res.result
      }
    })
  }
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNo = 1;
  getList();
}

/** 搜索按钮操作 */
function handleQueryPersonnel() {
  queryParamsPersonnel.value.pageNo = 1;
  getListPersonnel();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 重置按钮操作 */
function resetQueryPersonnel() {
  proxy.resetForm("queryRefPersonnel");
  handleQueryPersonnel();
}

/** 删除按钮操作 */
function handleDelete(row) {
  if (useUserStore().roles.includes("admin")) {
    let _ids = (row.id || ids.value).toString().split();
    proxy.$modal.confirm('是否确认删除编号为"' + _ids + '"的数据项?').then(function () {
      return delClue(_ids);
    }).then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    }).catch(() => { });
  } else {
    proxy.$modal.msgError("暂无权限");
  }
}

/** 帮定人员 */
function handlePersonnel(row) {
  if (useUserStore().roles.includes("admin")) {
    openPersonnel.value = true;
    getListPersonnel(row);
  } else {
    proxy.$modal.msgError("暂无权限");
  }

}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  multiple.value = !selection.length;
}

function handleCurrentChange(row) {
  curIds.value = row;
}

/** 多选框选中数据 */
function handleSelectionChangePersonnel(selection) {
  idsPersonnel = selection;
}

/** 重置新增的表单以及其他数据  */
function reset() {
  form.value = {
    id: undefined,
    sources: undefined,
    nature: undefined,
    clueValue: undefined,
    context: undefined,
    processingProgress: undefined,
    people:[]
  };
  proxy.resetForm("roleRef");
}

/** 添加线索 */
function handleAdd() {
  if (useUserStore().roles.includes("admin")) {
    reset();
    open.value = true;
    title.value = "添加线索";
  } else {
    proxy.$modal.msgError("暂无权限");
  }
}

/** 修改线索信息 */
function handleUpdate(row) {
  reset();
  if (useUserStore().roles.includes("admin")) {
    handleExpandChange(row, [row]).then(i => {
      let data = toRaw(clueList.value.filter(e => e.id == row.id)[0]);
      form.value = data;
      open.value = true;
    });
    title.value = "修改线索信息";
  } else {
    proxy.$modal.msgError("暂无权限");
  }
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["roleRef"].validate(valid => {
    if (valid) {
      if (form.value.id != undefined) {
        updateClue(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          let data = form.value.people.map(item => ({ 'sources_id': form.value.id,'user_id': item.id, 'personnelType': item.personnelType }))
          associationClue(data).then(response => {
            getList();
          });
        });
      } else {
        addClue(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

function submitFormPersonnel() {
  if (curIds.value.id != undefined) {
    let data = idsPersonnel.map(item => ({ 'sources_id': curIds.value.id,'user_id': item.id, 'personnelType': item.personnelType }))
    associationClue(data).then(response => {
      proxy.$modal.msgSuccess("修改成功");
      openPersonnel.value = false;
      getList();
    });
  }
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 取消按钮 */
function cancelpersonnel() {
  proxy.resetForm("queryRefPersonnel");
  openPersonnel.value = false;
  idsPersonnel = [];
}

getList();
</script>
